package com.example.apisix.plugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.apisix.plugin.runner.HttpRequest;
import org.apache.apisix.plugin.runner.HttpResponse;
import org.apache.apisix.plugin.runner.filter.PluginFilter;
import org.apache.apisix.plugin.runner.filter.PluginFilterChain;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TestPlugin implements PluginFilter {

    @Override
    public String name() {
        return "TestPlugin";
    }

    /**
     * 插件业务处理，修改请求body内容，然后再传给上游服务<br>
     * 注意：目前插件修改body是无法传递给上游服务。调用HttpRequest.setBody()方法只是把body传递给下一个插件用。调用HttpResponse.setBody()方法
     * 会执行完当前插件后，立马返回结果给调用方，不上传递给上游服务。<br>
     * 如果要修改body，只能用apisix提供的插件body-transformer
     * @param request 请求对象
     * @param response 响应对象
     * @param chain PluginFilterChain
     */
    @Override
    public void filter(HttpRequest request, HttpResponse response, PluginFilterChain chain) {
        String body = request.getBody();
        log.info("request body:" + body);

        // 在请求body添加用户id传给上游服务
        JSONObject jsonObject = JSON.parseObject(body);
        jsonObject.put("userId", 111L);
        jsonObject.put("userName", "apisix测试插件改写入参-" + jsonObject.get("userName"));
        String jsonString = jsonObject.toJSONString();
        log.info("插件修改后 request body:" + jsonString);

        request.setHeader("modify", "888");
        log.info("新增请求头：888");

        request.setBody(jsonString);
        chain.filter(request, response);
    }

    /**
     * 该方法要求apisix是否要把body传给组件。然后filter方法的HttpRequest#getBody获取body内容
     * @return true-要求请求body传给组件
     */
    @Override
    public Boolean requiredBody() {
        return true;
    }
}
